// pages/index/index.js
const app = getApp()

Page({
  data: {
    userInfo: null,
    currentTab: 0, // 0: 推荐, 1: 精选
    recommendUsers: [],
    featuredUsers: [],
    currentUserIndex: 0,
    currentUser: null,
    isLoading: true,
    hasMore: true,
    page: 1,
    showFixedHeader: false,
    scrollTop: 0,
    markers: [],
    polyline: [],
    showMessageModal: false,
    messageContent: ''
  },

  onLoad() {
    this.checkAuthAndLoadData();
  },

  onShow() {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo
      });
      if (this.data.recommendUsers.length === 0) {
        this.loadRecommendUsers();
      }
    }
  },

  // 检查授权并加载数据
  checkAuthAndLoadData() {
    if (app.globalData.userInfo) {
      this.setData({ userInfo: app.globalData.userInfo });
      this.loadRecommendUsers();
    } else {
      wx.redirectTo({
        url: '/pages/login/login'
      });
    }
  },

  // 切换选项卡
  switchTab(e) {
    const tab = parseInt(e.currentTarget.dataset.tab);
    this.setData({
      currentTab: tab,
      currentUserIndex: 0
    });
    
    // 根据选项卡加载对应数据
    if (tab === 0 && this.data.recommendUsers.length === 0) {
      this.loadRecommendUsers();
    } else if (tab === 1 && this.data.featuredUsers.length === 0) {
      this.loadFeaturedUsers();
    } else {
      this.showCurrentUser();
    }
  },

  // 加载推荐用户
  loadRecommendUsers() {
    this.setData({ isLoading: true });

    setTimeout(() => {
      const mockUsers = this.generateMockUsers('recommend');
      this.setData({
        recommendUsers: mockUsers,
        hasMore: false,
        isLoading: false
      });
      this.showCurrentUser();
    }, 500);
  },

  // 加载精选用户
  loadFeaturedUsers() {
    this.setData({ isLoading: true });

    setTimeout(() => {
      const mockUsers = this.generateMockUsers('featured');
      this.setData({
        featuredUsers: mockUsers,
        hasMore: false,
        isLoading: false
      });
      this.showCurrentUser();
    }, 500);
  },


  // 生成模拟用户数据
  generateMockUsers(type = 'recommend') {
    const baseUsers = [
      {
        id: '1001',
        nickname: '阳光男孩',
        age: 26,
        gender: 'male',
        city: '上海',
        school: '复旦大学',
        verified: true,
        avatar_url: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=400&h=400&fit=crop&crop=face',
        introduction: '热爱运动，喜欢篮球和健身。性格开朗，工作稳定，希望找到志同道合的另一半。',
        tags: ['运动', '篮球', '健身', '游泳', '爬山', '骑行'],
        photos: ['https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=800&h=800&fit=crop&crop=face'],
        basic_info: ['身高178cm', '月收入3-5万', '定居上海', '不抽烟', '不喝酒', '有房有车'],
        certifications: [
          { type: 'avatar', name: '头像', status: 'passed' },
          { type: 'realname', name: '实名', status: 'passed' },
          { type: 'education', name: '学历', status: 'passed' }
        ],
        life_photo: 'https://images.unsplash.com/photo-1544005313-94ddf0286df2?w=800&h=800&fit=crop&crop=center',
        additional_life_photos: [
          'https://images.unsplash.com/photo-1514888286974-6c03e2ca1dba?w=800&h=800&fit=crop&crop=center',
          'https://images.unsplash.com/photo-1517423568366-8b83523034fd?w=800&h=800&fit=crop&crop=center'
        ],
        favorite_sports: ['篮球', '健身', '游泳'],
        sports_photos: [
          'https://images.unsplash.com/photo-1546519638-68e109498ffc?w=800&h=800&fit=crop&crop=center',
          'https://images.unsplash.com/photo-1536922246289-88c42f957773?w=800&h=800&fit=crop&crop=center'
        ],
        personality_type: {
          name: '执行官',
          mbti: 'ESFJ',
          key_points: ['外向热情', '注重实际', '乐于助人', '责任心强'],
          description: '执行官类型的人通常外向、热情、注重实际，他们乐于帮助他人，有很强的责任心和组织能力。在团队中往往是协调者和组织者，善于建立和谐的人际关系。',
          relationship_description: '在亲密关系中，执行官类型的人非常忠诚和体贴，他们重视家庭和稳定的关系。会主动关心伴侣的需求，努力营造温馨和谐的家庭氛围，是可靠的生活伴侣。'
        },
        ip_location: {
          province: '浙江省',
          city: '杭州市',
          coordinates: [120.1551, 30.2741]
        }
      },
      {
        id: '1002',
        nickname: '文艺青年',
        age: 25,
        gender: 'male',
        city: '杭州',
        school: '浙江大学',
        verified: true,
        avatar_url: 'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=400&h=400&fit=crop&crop=face',
        introduction: '喜欢读书和音乐，寻找志同道合的朋友。享受安静的时光，也热爱户外的阳光。',
        tags: ['读书', '音乐', '电影', '绘画', '写作', '咖啡'],
        photos: ['https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=800&h=800&fit=crop&crop=face'],
        basic_info: ['身高180cm', '月收入2-3万', '定居杭州', '不抽烟', '不喝酒', '喜欢小动物'],
        certifications: [
          { type: 'avatar', name: '头像', status: 'passed' },
          { type: 'realname', name: '实名', status: 'failed' },
          { type: 'education', name: '学历', status: 'passed' }
        ],
        life_photo: 'https://images.unsplash.com/photo-1517841905240-472988babdf9?w=800&h=800&fit=crop&crop=center',
        additional_life_photos: [
          'https://images.unsplash.com/photo-1517423738875-5ce310acd3da?w=800&h=800&fit=crop&crop=center',
          'https://images.unsplash.com/photo-1517423447168-cb804aafa6e0?w=800&h=800&fit=crop&crop=center'
        ],
        favorite_sports: ['瑜伽', '徒步', '羽毛球'],
        sports_photos: [
          'https://images.unsplash.com/photo-1544367567-0f2fcb009e0b?w=800&h=800&fit=crop&crop=center',
          'https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?w=800&h=800&fit=crop&crop=center'
        ],
        personality_type: {
          name: '调停者',
          mbti: 'INFP',
          key_points: ['理想主义', '富有同情心', '创造力强', '追求和谐'],
          description: '调停者类型的人通常理想主义、富有同情心，他们具有很强的创造力和想象力。追求内心的和谐与意义，重视个人价值观，善于理解他人的情感需求。',
          relationship_description: '在亲密关系中，调停者类型的人非常浪漫和理想主义，他们追求深刻的情感连接。会用心理解伴侣的内心世界，重视精神层面的交流，是温柔体贴的伴侣。'
        },
        ip_location: {
          province: '浙江省',
          city: '杭州市',
          coordinates: [120.1551, 30.2741]
        }
      },
      {
        id: '1003',
        nickname: '运动达人',
        age: 28,
        gender: 'male',
        city: '深圳',
        school: '深圳大学',
        verified: true,
        avatar_url: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400&h=400&fit=crop&crop=face',
        introduction: '热爱各种户外运动，马拉松爱好者。性格开朗，喜欢结交新朋友。',
        tags: ['跑步', '健身', '游泳', '爬山', '骑行', '羽毛球'],
        photos: ['https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=800&h=800&fit=crop&crop=face'],
        basic_info: ['身高182cm', '月收入4-6万', '定居深圳', '不抽烟', '偶尔喝酒', '有房'],
        certifications: [
          { type: 'avatar', name: '头像', status: 'passed' },
          { type: 'realname', name: '实名', status: 'passed' },
          { type: 'education', name: '学历', status: 'failed' }
        ],
        life_photo: 'https://images.unsplash.com/photo-1511988617509-a57c8a288659?w=800&h=800&fit=crop&crop=center',
        additional_life_photos: [
          'https://images.unsplash.com/photo-1517423568366-8b83523034fd?w=800&h=800&fit=crop&crop=center',
          'https://images.unsplash.com/photo-1517423447168-cb804aafa6e0?w=800&h=800&fit=crop&crop=center'
        ],
        favorite_sports: ['马拉松', '健身', '游泳', '骑行'],
        sports_photos: [
          'https://images.unsplash.com/photo-1558618047-3c8c76ca7d13?w=800&h=800&fit=crop&crop=center',
          'https://images.unsplash.com/photo-1574680178050-55c6a6a96e0a?w=800&h=800&fit=crop&crop=center'
        ],
        personality_type: {
          name: '探险家',
          mbti: 'ESTP',
          key_points: ['行动派', '适应力强', '热爱冒险', '注重当下'],
          description: '探险家类型的人通常是行动派，适应力强，热爱冒险和挑战。他们注重当下的体验，善于在现实环境中快速反应，充满活力和热情。',
          relationship_description: '在亲密关系中，探险家类型的人充满活力和激情，他们喜欢与伴侣一起尝试新鲜事物。重视当下的快乐体验，善于营造轻松愉快的氛围，是充满惊喜的伴侣。'
        },
        ip_location: {
          province: '浙江省',
          city: '杭州市',
          coordinates: [120.1551, 30.2741]
        }
      }
    ];

    if (type === 'featured') {
      return baseUsers.map(user => ({
        ...user,
        is_featured: true,
        featured_reason: '高匹配度用户'
      }));
    }

    return baseUsers;
  },

  // 跳过用户
  skipUser() {
    if (this.data.currentUserIndex < this.getCurrentUsers().length - 1) {
      this.setData({
        currentUserIndex: this.data.currentUserIndex + 1
      });
      this.showCurrentUser();
    } else {
      // 没有更多用户了
      this.setData({
        currentUser: null
      });
      wx.showToast({
        title: '没有更多用户了',
        icon: 'none'
      });
    }
  },

  // 喜欢用户
  likeUser() {
    const currentUser = this.data.currentUser;
    if (!currentUser) return;

    // 保存到喜欢列表
    this.saveLikedUser(currentUser);
    
    // 显示成功提示
    wx.showToast({
      title: '喜欢成功',
      icon: 'success'
    });

    // 显示下一个用户
    this.skipUser();
  },

  // 保存喜欢的用户
  saveLikedUser(user) {
    // 获取现有的喜欢列表
    let likedUsers = wx.getStorageSync('likedUsers') || [];
    
    // 检查是否已经喜欢过这个用户
    const existingIndex = likedUsers.findIndex(u => u.id === user.id);
    if (existingIndex === -1) {
      // 添加时间戳
      const likedUser = {
        ...user,
        liked_time: new Date().toISOString()
      };
      likedUsers.push(likedUser);
      
      // 保存到本地存储
      wx.setStorageSync('likedUsers', likedUsers);
      
      // 更新全局数据
      if (app.globalData.likedUsers) {
        app.globalData.likedUsers = likedUsers;
      }
    }
  },

  // 获取当前用户列表
  getCurrentUsers() {
    return this.data.currentTab === 0 ? this.data.recommendUsers : this.data.featuredUsers;
  },

  // 刷新推荐
  refreshRecommend() {
    this.setData({ 
      page: 1,
      currentUserIndex: 0
    });
    if (this.data.currentTab === 0) {
      this.loadRecommendUsers();
    } else {
      this.loadFeaturedUsers();
    }
  },

  // 预览头像 - 全屏显示
  previewAvatar() {
    if (!this.data.currentUser) return;
    
    const avatarUrl = this.data.currentUser.avatar_url || '/images/default-avatar.png';
    wx.previewImage({
      urls: [avatarUrl],
      current: avatarUrl,
      success: () => {
        console.log('头像预览成功');
      },
      fail: (err) => {
        console.error('头像预览失败:', err);
        wx.showToast({
          title: '预览失败',
          icon: 'none'
        });
      }
    });
  },

  // 预览照片 - 全屏显示
  previewPhoto() {
    if (!this.data.currentUser || !this.data.currentUser.photos || this.data.currentUser.photos.length === 0) return;
    
    const photoUrl = this.data.currentUser.photos[0];
    wx.previewImage({
      urls: [photoUrl],
      current: photoUrl,
      success: () => {
        console.log('照片预览成功');
      },
      fail: (err) => {
        console.error('照片预览失败:', err);
        wx.showToast({
          title: '预览失败',
          icon: 'none'
        });
      }
    });
  },

  // 预览生活照片 - 全屏显示
  previewLifePhoto() {
    if (!this.data.currentUser || !this.data.currentUser.life_photo) return;
    
    const lifePhotoUrl = this.data.currentUser.life_photo;
    wx.previewImage({
      urls: [lifePhotoUrl],
      current: lifePhotoUrl,
      success: () => {
        console.log('生活照片预览成功');
      },
      fail: (err) => {
        console.error('生活照片预览失败:', err);
        wx.showToast({
          title: '预览失败',
          icon: 'none'
        });
      }
    });
  },

  // 预览运动照片 - 全屏显示
  previewSportsPhoto(e) {
    if (!this.data.currentUser || !this.data.currentUser.sports_photos || this.data.currentUser.sports_photos.length === 0) return;
    
    const index = e.currentTarget.dataset.index;
    const sportsPhotos = this.data.currentUser.sports_photos;
    wx.previewImage({
      urls: sportsPhotos,
      current: sportsPhotos[index],
      success: () => {
        console.log('运动照片预览成功');
      },
      fail: (err) => {
        console.error('运动照片预览失败:', err);
        wx.showToast({
          title: '预览失败',
          icon: 'none'
        });
      }
    });
  },

  // 预览更多生活照片 - 全屏显示
  previewAdditionalLifePhoto(e) {
    if (!this.data.currentUser || !this.data.currentUser.additional_life_photos || this.data.currentUser.additional_life_photos.length === 0) return;
    
    const index = e.currentTarget.dataset.index;
    const additionalLifePhotos = this.data.currentUser.additional_life_photos;
    wx.previewImage({
      urls: additionalLifePhotos,
      current: additionalLifePhotos[index],
      success: () => {
        console.log('更多生活照片预览成功');
      },
      fail: (err) => {
        console.error('更多生活照片预览失败:', err);
        wx.showToast({
          title: '预览失败',
          icon: 'none'
        });
      }
    });
  },

  // 发送小纸条 - 显示留言框
  sendNote() {
    const currentUser = this.data.currentUser;
    if (!currentUser) return;

    this.setData({
      showMessageModal: true,
      messageContent: ''
    });
  },

  // 关闭留言框
  closeMessageModal() {
    this.setData({
      showMessageModal: false,
      messageContent: ''
    });
  },

  // 输入留言内容
  onMessageInput(e) {
    this.setData({
      messageContent: e.detail.value
    });
  },

  // 发送小纸条
  sendMessage() {
    const currentUser = this.data.currentUser;
    const messageContent = this.data.messageContent.trim();
    
    if (!messageContent) {
      wx.showToast({
        title: '请输入留言内容',
        icon: 'none'
      });
      return;
    }

    // 模拟发送小纸条
    console.log('发送小纸条给:', currentUser.nickname, '内容:', messageContent);
    
    wx.showToast({
      title: '小纸条已发送',
      icon: 'success',
      duration: 1500
    });

    // 关闭留言框
    this.closeMessageModal();
  },

  // 滚动监听 - 固定头部显示
  onPageScroll(e) {
    const scrollTop = e.scrollTop;
    const threshold = 50; // 滚动阈值，超过50rpx时显示固定头部
    
    if (scrollTop > threshold && !this.data.showFixedHeader) {
      this.setData({
        showFixedHeader: true
      });
    } else if (scrollTop <= threshold && this.data.showFixedHeader) {
      this.setData({
        showFixedHeader: false
      });
    }
  },

  // 地图区域变化监听
  onMapRegionChange(e) {
    console.log('地图区域变化:', e);
  },

  // 配置地图 - 只显示省份级别
  setupMapMarkers(location) {
    if (!location) return;
    
    // 清空标记和覆盖物，只显示省份级别的地图
    this.setData({
      markers: [],
      polyline: []
    });
  },

  // 显示当前用户时设置地图
  showCurrentUser() {
    let users = [];
    if (this.data.currentTab === 0) {
      users = this.data.recommendUsers;
    } else {
      users = this.data.featuredUsers;
    }

    if (users.length > 0 && this.data.currentUserIndex < users.length) {
      const currentUser = users[this.data.currentUserIndex];
      this.setData({
        currentUser: currentUser
      });
      
      // 设置地图标记
      if (currentUser.ip_location) {
        this.setupMapMarkers(currentUser.ip_location);
      }
    } else {
      this.setData({
        currentUser: null
      });
    }
  }
})
